package Dao.impl;/*
 *徐韬
 *2021/9/21
 *12:36
 */

import Dao.EmpDao;
import Util.DruidUitl;
import Util.Page;
import entity.Emp;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.lang.model.element.QualifiedNameable;
import java.sql.SQLException;
import java.util.List;

public class EmpDaoimpl implements EmpDao {
    QueryRunner queryRunner = new QueryRunner();

    @Override
    public List<Emp> selectAll() {
        try {
            return queryRunner.query(DruidUitl.getConnection(),"select * from emp",new BeanListHandler<>(Emp.class));
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"在查询所有时出现异常");
        }
    }

    @Override
    public List<Emp> selectAllByPage(Page page) {
        try {
            return queryRunner.query(DruidUitl.getConnection(),"select * from Emp limit ?,?",new BeanListHandler<>(Emp.class),page.getStartow(),page.getPagesize());
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"在分页时出现异常");
        }
    }

    @Override
    public Long selectcount() {
        try {
            return queryRunner.query(DruidUitl.getConnection(),"select count(*) from Emp;",new ScalarHandler<>());
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"在计算总行数时出现异常");
        }
    }

    @Override
    public int insert(Emp emp) {
        Object[] params = {emp.getName(),emp.getSalay(),emp.getAge()};
        try {
            return queryRunner.update(DruidUitl.getConnection(),"insert into Emp(name,salay,age) values(?,?,?)",params);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"在添加员工信息时出现异常");
        }
    }

    @Override
    public Emp select(Integer id) {
        try {
            return queryRunner.query(DruidUitl.getConnection(),"select * from Emp where id = ?",new BeanHandler<>(Emp.class ),id);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"在查询单个员工信息时出现异常");
        }
    }

    @Override
    public int update(Emp emp) {
        Object[] params = {emp.getName(),emp.getSalay(),emp.getAge(),emp.getId()};
        try {
            return queryRunner.update(DruidUitl.getConnection(),"update emp set name=?,salay=?,age=? where id=?",params);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"在修改员工信息时出现异常");
        }
    }

    @Override
    public int delete(Integer id) {
        try {
            return queryRunner.update(DruidUitl.getConnection(),"delete from Emp where id=?",id);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"在删除员工时出现异常");
        }
    }
}
